package com.mystore.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mystore.framework.mapper.AppMapper;
import com.mystore.framework.mapper.AppModelMapper;
import com.mystore.framework.pojo.AppModel;
import com.mystore.framework.pojo.User;
import icu.mhb.mybatisplus.plugln.base.mapper.JoinBaseMapper;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
public class IAppModelServiceImpl extends IBaseServiceImpl<AppModelMapper,AppModel>{
    @Resource
    private IAppServiceImpl iAppServiceImpl;
    @Transactional
    public int insertOne(AppModel t) {
        return baseMapper.insert(t)==0?0:t.getAppModelId();
    }
    @Override
    public IPage<AppModel> selectPageByData(String data, Page<AppModel> page) {
        QueryWrapper<AppModel> queryWrapper=new QueryWrapper<>();
        queryWrapper.apply("(CONCAT_WS('-',app_model_id,app_id,app_version,app_platform,file_model_id)) LIKE {0}","%"+data+"%");
        return baseMapper.selectPage(page,queryWrapper);
    }
    public List<AppModel> selectByAppId(int appId){
        QueryWrapper<AppModel> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("app_id",appId);
        return baseMapper.selectList(queryWrapper);
    }
    @Transactional
    public boolean insertApps(int appId,String appVersion,String[] appPlatform,int [] fileModelIds){
        if(appPlatform.length!=fileModelIds.length)
            return false;
        else {
            boolean result=true;
            for(int i=0;i<appPlatform.length;i++){
                AppModel appModel=new AppModel();
                appModel.setAppId(appId);
                appModel.setAppVersion(appVersion);
                appModel.setAppPlatform(appPlatform[i]);
                appModel.setFileModelId(fileModelIds[i]);
                if(baseMapper.insert(appModel)<=0)
                    result=false;
            }
            if (result) {
                iAppServiceImpl.updateOne(iAppServiceImpl.selectById(appId));
            }
            return result;
        }
    }
    @Transactional
    public boolean deleteByAppId(int appId){
        QueryWrapper<AppModel> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("app_id",appId);
        List<AppModel> appModels=baseMapper.selectList(queryWrapper);
        if(appModels==null||appModels.isEmpty())
            return true;
        return baseMapper.delete(new QueryWrapper<AppModel>().eq("app_id",appId))>0;
    }
}
